import json
import requests
from fastapi import Body, FastAPI
from pydantic import BaseModel
import uvicorn
import asyncio


class User(BaseModel):
    code: str


app = FastAPI()


@app.get("/test")
def index():
    return {"data": "hello world"}


@app.post("/users")
def index():
    return {"data": "hello world"}


@app.api_route("/items/", methods=["get", "post", "put"])
def items():
    return [{"data": "hello world"}]


@app.get("/")
def get_public_ip():
    response = requests.get("http://httpbin.org/ip")
    data = response.json()
    ip = data["origin"]
    return ip


headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Pragma": "no-cache",
    "User-Agent": "self-defind-user-agent",
    "Cookie": "name=self-define-cookies-in header",
    "X-Requested-With": "XMLHttpRequest",
}


def send_get(url: str):
    try:
        # 注意：用res.content，不用res.text，否则会有中文乱码
        res = requests.get(url=url, headers=headers)
        # result = res.text.encode('utf-8').decode("unicode_escape")
        # print('---------result=', result, res.text)
        return json.loads(res.content.decode("utf-8").encode("utf-8"))
    except Exception as e:
        print("[send_get]Failed to json.load, {0}".format(e))
        return {}


APPID = "wxd989ed601a0c4637"
SECRET = "defc243621732981fea2bc494889300d"


@app.post("/getOpenid")
def getOpenid(user: User):
    print(user.code)

    url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code".format(
        APPID, SECRET, user.code
    )
    result = send_get(url)
    print(result)
    return {"data": result, "code": 1}


@app.post("/getPhone")
def getPhoneNumber(user: User):
    code = user.code

    # 获取access_token
    # access_token = AccessToken.objects.get(appname='xxx')

    token = getAcessToken()

    url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={token}"
    headers = {"Content-Type": "application/json"}
    para = {"code": code}
    response = requests.post(url, json=para, headers=headers)

    res = response.json()

    if res["errcode"] == 0:  # 成功获取phonenumber
        phone = res["phone_info"]["phoneNumber"]
        return {"data": {"data": phone}, "code": 1}

    else:
        return {"code": -1, "phone": -1}


def getAcessToken():
    # 获取access_token
    url = (
        "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
        % (APPID, SECRET)
    )
    res = requests.get(url)
    token = json.loads(res.text)["access_token"]
    return token


# Define a startup event handler
def startup_event():
    print("Application startup event")


# Register the startup event handler
app.add_event_handler("startup", startup_event)


# Define a shutdown event handler
def shutdown_event():
    print("Application shutdown event")


# Register the shutdown event handler
app.add_event_handler("shutdown", shutdown_event)

uvicorn.run(app, host="0.0.0.0", port=5555)
